﻿using CPF;
using CPF.Animation;
using CPF.Charts;
using CPF.Controls;
using CPF.Drawing;
using CPF.Input;
using CPF.Mac.Foundation;
using CPF.Shapes;
using CPF.Styling;
using CPF.Svg;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace CPFUI.IControl
{
    [CPF.Design.DesignerLoadStyle("res://$safeprojectname$/Stylesheet1.css")]//用于设计的时候加载样式
    public class MacMenu : Control
    {
        public MacMenu()
        {
            Container = new StackPanel()
            {
                Orientation= Orientation.Horizontal,
                Height = 110,
                MarginLeft = 0,
                MarginRight = 0,
                MarginBottom = 0,

            }; ShowType = MacMenuShowType.Botton;
        }
        //模板定义
        protected override void InitializeComponent()
        {
            Children.Add(Container);
        }
        StackPanel Container;
        #region 属性
        [Description("显示位置"), DefaultValue(MacMenuShowType.Botton)]
        public MacMenuShowType ShowType
        {
            get { return (MacMenuShowType)GetValue(); }
            set
            {
                SetValue(value);
                switch (value)
                {
                    case MacMenuShowType.Botton:
                        Container.Orientation = Orientation.Horizontal;
                        break;
                    case MacMenuShowType.Top:
                        Container.Orientation = Orientation.Horizontal;
                        break;
                    case MacMenuShowType.Left:
                        Container.Orientation = Orientation.Vertical;
                        break;
                    case MacMenuShowType.Right:
                        Container.Orientation = Orientation.Vertical;
                        break;
                }
                List<UIElement> items = Container.GetChildren().ToList();
                double left = Spacing;
                for (int i = 0; i < items.Count; i++)
                {
                    MacMenuItem otherItem = (MacMenuItem)items[i];
                    otherItem.ShowType= ShowType;
                    SetShowType(otherItem);
                }
                if (ShowType == MacMenuShowType.Botton || ShowType == MacMenuShowType.Top)
                {
                    LeaveAnimation();

                }
                else
                {
                    LeaveAnimationLeftRight();
                }
            }
        }
        /// <summary>
        /// 移动滚动条左侧偏移值
        /// </summary>
        [Description("按钮间距"), DefaultValue(0)]
        public double Spacing
        {
            get { return (double)GetValue(); }
            set { SetValue(value); }
        }
        [Description("缩放系数"), DefaultValue(2)]
        public double ChangedCoefficient
        {

            get { return (double)GetValue(); }
            set { SetValue(value); }
        }

        [Description("Mac按钮缩放最大大小"),DefaultValue(200)]
        public double MaxSize
        {
            get { return (double)GetValue(); }
            set { SetValue(value); }
        }

        [Description("Mac按钮缩放最小大小"),DefaultValue(80)]
        public double MinSize
        {
            get { return (double)GetValue(); }
            set { SetValue(value); }
        }
        #endregion
#if !DesignMode //用户代码写到这里，设计器下不执行，防止设计器出错
        protected override void OnInitialized()
        {
            base.OnInitialized();
            Container.MouseMove += Container_MouseMove;
            Container.MouseLeave += Container_MouseLeave;
        }

        private bool IsfirstEnter = true;
        private void Container_MouseLeave(object sender, CPF.Input.MouseEventArgs e)
        {

            IsfirstEnter = true;
            HoveIndex = -1; 
            if (ShowType == MacMenuShowType.Botton || ShowType == MacMenuShowType.Top)
            {
                LeaveAnimation();
            }
            else
            {
                LeaveAnimationLeftRight();
            }
        }
        private Point _mouseMovePoint=new Point(0,0);
        private void Container_MouseMove(object sender, CPF.Input.MouseEventArgs e)
        {
            if (IsfirstEnter)
            {

            }
            if(Math.Abs(Math.Abs(_mouseMovePoint.X)- Math.Abs(e.Location.X)) < 2&& Math.Abs(Math.Abs(_mouseMovePoint.Y) - Math.Abs(e.Location.Y)) < 2)
            {
                return;
            }
            _mouseMovePoint = e.Location;
            if (ShowType == MacMenuShowType.Botton || ShowType == MacMenuShowType.Top)
            {

                EnterAnimotionTopBottom(e.Location);
            }
            else
            {
                EnterAnimotionLeftRight(e.Location);
            }
            //IsfirstEnter = false;
        }
        private void Item_MouseDown(object sender, CPF.Input.MouseButtonEventArgs e)
        {
            MacMenuItem item = sender as MacMenuItem;
            ClickAnimation(item, 0.5f);
            MacItemMouseDown?.Invoke(sender, e);
        }

        //用户代码
        /// <summary>
        /// 添加Item
        /// </summary>
        /// <param name="item"></param>
        public void AddMacMenuItem(MacMenuItem item)
        {
            item.Width = MinSize;
            item.Height = MinSize + 40;
            item.MarginLeft = Spacing;
            item.IsEnter = Visibility.Hidden;
            item.ShowType = ShowType;
            item.MarginBottom = 0;
            item.MouseDown += Item_MouseDown;
            item.MouseEnter += Item_MouseEnter;
            item.MouseLeave += Item_MouseLeave;
            Container.Children.Add(item);
            if (ShowType == MacMenuShowType.Botton || ShowType == MacMenuShowType.Top)
            {
                LeaveAnimation();
            }
            else
            {
                LeaveAnimationLeftRight();
            }
        }

        private void Item_MouseLeave(object sender, MouseEventArgs e)
        {
            MacMenuItem item= sender as MacMenuItem;
            item.IsEnter = Visibility.Hidden;
        }

        private void Item_MouseEnter(object sender, MouseEventArgs e)
        {
            MacMenuItem item = sender as MacMenuItem;
            item.IsEnter = Visibility.Visible;
        }


        /// <summary>
        /// 重新设置所有Item坐标位置
        /// </summary>
        public void SetAllItemPosition()
        {
            double width = 0;
            double maxHeight = 0;

            List<UIElement> items = Container.GetChildren().ToList();
            for (int i = 0; i < items.Count; i++)
            {
                if (items[i] is MacMenuItem)
                {
                    width += items[i].ActualSize.Width+ Spacing;
                    if (items[i].ActualSize.Height > maxHeight)
                    {
                        maxHeight = items[i].ActualSize.Height;
                    }
                }
            }
            width = width - Spacing;

            Container.MarginBottom = 0;

            Container.Width = width + 20;
            Container.Height = maxHeight;

            IsfirstEnter=false;
        }
        public void SetAllItemPositionLeftRight()
        {
            double height = 0;
            double maxwidth = 0;

            List<UIElement> items = Container.GetChildren().ToList();
            for (int i = 0; i < items.Count; i++)
            {
                if (items[i] is MacMenuItem)
                {
                    height += items[i].ActualSize.Height + Spacing;
                    if (items[i].ActualSize.Width > maxwidth)
                    {
                        maxwidth = items[i].ActualSize.Width;
                    }
                }
            }
            height = height - Spacing;

            Container.MarginBottom = 0;

            Container.Height = height + 20;
            Container.Width = maxwidth;

            IsfirstEnter = false;
        }
        public int HoveIndex = -1;
        /// <summary>
        /// 鼠标移入时的放大动画
        /// </summary>
        /// <param name="e"></param>
        public void EnterAnimotionTopBottom(Point e)
        {
            List<UIElement> items = Container.GetChildren().ToList();
            double left = Spacing;
            for (int i = 0; i < items.Count; i++)
            {
                MacMenuItem otherItem = (MacMenuItem)items[i];
                
                if (otherItem.MenuItemType == MacMenuItemType.Separator)
                {
                    left += otherItem.Width.Value + Spacing;
                    continue;
                }
                //获取控件按钮中心位置点X
                double x = left + otherItem.Width.Value * 1.0 / 2;
                //获取控件按钮中心位置点Y
                double y =  otherItem.Height.Value * 1.0 / 2 + Container.Height.Value;
                //获取鼠标当前位置X
                double px = e.X - x;
                //获取鼠标当前位置Y
                double py = MinSize;
                //求XY坐标的平方根
                double sq = Math.Sqrt(Math.Pow(px, 2) + Math.Pow(py, 2));
                //计算缩放比例
                double scale = 1 - sq / (MaxSize * ChangedCoefficient);
                if (scale < 0)
                {
                    scale = 0;
                }
                double w= MinSize + (int)(scale * (MaxSize - MinSize));
                double h = w + 40; 
                otherItem.Width = w;
                otherItem.Height = h;//(int)(scale * MaxSize + 30);
                left += otherItem.Width.Value + Spacing;
                
                
                //otherItem.Width = MinSize + (int)(scale * (MaxSize - MinSize));
                //otherItem.Height = otherItem.Width + 30;//(int)(scale * MaxSize + 30);
                //LayoutContent();
                SetShowType(otherItem);
            }
            SetAllItemPosition();
        }
        public void EnterAnimotionLeftRight(Point e)
        {
            List<UIElement> items = Container.GetChildren().ToList();
            double top = Spacing;
            for (int i = 0; i < items.Count; i++)
            {
                MacMenuItem otherItem = (MacMenuItem)items[i];

                if (otherItem.MenuItemType == MacMenuItemType.Separator)
                {
                    top += otherItem.Height.Value + Spacing;
                    continue;
                }
                //获取控件按钮中心位置点X
                double x = top + otherItem.Height.Value * 1.0 / 2;
                //获取控件按钮中心位置点Y
                double y = otherItem.Width.Value * 1.0 / 2 + Container.Width.Value;
                //获取鼠标当前位置X
                double px = e.Y - x;
                //获取鼠标当前位置Y
                double py = MinSize;
                //求XY坐标的平方根
                double sq = Math.Sqrt(Math.Pow(px, 2) + Math.Pow(py, 2));
                //计算缩放比例
                double scale = 1 - sq / (MaxSize * ChangedCoefficient);
                if (scale < 0)
                {
                    scale = 0;
                }
                double h = MinSize + (int)(scale * (MaxSize - MinSize));
                double w = h + 40;
                otherItem.Width = w;
                otherItem.Height = h;//(int)(scale * MaxSize + 30);
                top += otherItem.Height.Value + Spacing;


                //otherItem.Width = MinSize + (int)(scale * (MaxSize - MinSize));
                //otherItem.Height = otherItem.Width + 30;//(int)(scale * MaxSize + 30);
                //LayoutContent();
                SetShowType(otherItem);
            }
            SetAllItemPositionLeftRight();
        }

        /// <summary>
        /// 离开时的动画缩放
        /// </summary>
        public void LeaveAnimation(bool isAnimation = true)
        {
            double width = 0;
            double maxHeight = 0;

            List<UIElement> items = Container.GetChildren().ToList();
            for (int i = 0; i < items.Count; i++)
            {
                MacMenuItem item = (MacMenuItem)items[i];
                if (items[i] is MacMenuItem)
                {
                    if (item.MenuItemType == MacMenuItemType.Separator)
                    {
                        width += item.Width.Value+ Spacing;
                    }
                    else{ width += MinSize + Spacing; }
                    
                }
            }
            width = width - Spacing;
            double containerWidth = width+20;// (width < 300 ? 300 : width + 120) + 100;
            double containerHeight = MinSize + 40;

            if (isAnimation)
            {

                Animation(Container, containerWidth, containerHeight,
                    0.1);
            }
            else
            {
                Container.Width = containerWidth;
                Container.Height = containerHeight;

            }

            for (int i = 0; i < items.Count; i++)
            {
                MacMenuItem item = (MacMenuItem)items[i];
                if (item != null)
                {
                    if (item.MenuItemType == MacMenuItemType.Separator)
                    {
                        if (isAnimation)
                        {
                            Animation(item, 5, MinSize + 40,
                            0.1);
                        }
                        else
                        {
                            item.Width = 5;
                            item.Width = MinSize + 40;
                        }
                    }
                    else
                    {
                        if (isAnimation)
                        {
                            Animation(item, MinSize, MinSize + 40,
                            0.1);
                        }
                        else
                        {
                            item.Width = MinSize ;
                            item.Width = MinSize + 40;
                        }
                    }


                }
            }



        }
        public void LeaveAnimationLeftRight(bool isAnimation=true)
        {
            double height = 0;
            double maxWidth = 0;

            List<UIElement> items = Container.GetChildren().ToList();
            for (int i = 0; i < items.Count; i++)
            {
                MacMenuItem item = (MacMenuItem)items[i];
                if (items[i] is MacMenuItem)
                {
                    item.MarginBottom = Spacing;
                    if (item.MenuItemType == MacMenuItemType.Separator)
                    {
                        height += item.Height.Value + Spacing;
                    }
                    else { height += MinSize + Spacing; }

                }
            }
            height = height - Spacing;
            double containerHeight = height + 20;// (width < 300 ? 300 : width + 120) + 100;
            double containerWidth = MinSize + 40;
            if (isAnimation)
            {
                Animation(Container, containerWidth, containerHeight,
                0.1);
            }
            else
            {
                Container.Width = containerWidth;
                Container.Height = containerHeight;
            }
            for (int i = 0; i < items.Count; i++)
            {
                MacMenuItem item = (MacMenuItem)items[i];
                if (item != null)
                {
                    if (item.MenuItemType == MacMenuItemType.Separator)
                    {
                        if (isAnimation)
                        {
                            Animation(item, MinSize + 40, 5,
                            0.1);
                        }
                        else
                        {
                            item.Width = MinSize + 40;
                            item.Width =5;

                        }
                    }
                    else
                    {
                        if (isAnimation)
                        {
                            Animation(item, MinSize + 40, MinSize,
                            0.1);
                        }
                        else
                        {
                            item.Width = MinSize + 40;
                            item.Width = MinSize;

                        }
                    }


                }
            }
        }

        public void Animation(CpfObject obj,double width,double height,double left, double time)
        {
            var storyboard = new Storyboard
            {
                Timelines =
                {
                    new Timeline(1)
                    {
                        KeyFrames =
                        {
                            new KeyFrame<FloatField> { Property = nameof(Control.Width), Value =width},
                            new KeyFrame<FloatField> { Property = nameof(Control.Height), Value =height },
                            new KeyFrame<FloatField> { Property = nameof(Control.MarginLeft), Value =left }
                        },
                    }
                }
            };

            storyboard.Start(obj, TimeSpan.FromSeconds(time), 1, EndBehavior.Reservations);
        }
        public void Animation(CpfObject obj, double width, double height, double time)
        {
            var storyboard = new Storyboard
            {
                Timelines =
                {
                    new Timeline(1)
                    {
                        KeyFrames =
                        {
                            new KeyFrame<FloatField> { Property = nameof(Control.Width), Value =width},
                            new KeyFrame<FloatField> { Property = nameof(Control.Height), Value =height },
                        },
                    }
                }
            };

            storyboard.Start(obj, TimeSpan.FromSeconds(time), 1, EndBehavior.Reservations);
        }
        public void Animation(CpfObject obj, double width, double height, double time, Action fun)
        {
            var storyboard = new Storyboard
            {
                Timelines =
                {
                    new Timeline(1)
                    {
                        KeyFrames =
                        {
                            new KeyFrame<FloatField> { Property = nameof(Control.Width), Value =width},
                            new KeyFrame<FloatField> { Property = nameof(Control.Height), Value =height },
                        },
                    }
                }
            };

            storyboard.Start(obj, TimeSpan.FromSeconds(time), 1, EndBehavior.Reservations);
            storyboard.Completed += (s, e) =>
            {
                fun();
            };
        }
        public void ClickAnimation(Control obj, double time = 0.5)
        {
            string name = "";
            int value = 30;
            switch (ShowType)
            {
                case MacMenuShowType.Top:
                    name = "MarginTop";
                    break;
                case MacMenuShowType.Right:
                    name = "MarginRight"; 
                    break;
                case MacMenuShowType.Botton:
                    name= "MarginBottom"; 
                    break;
                case MacMenuShowType.Left:
                    name = "MarginLeft"; 
                    break;
            }
            var storyboard1 = new Storyboard
            {
                Timelines =
                {
                    new Timeline(0.7f)
                    {
                        KeyFrames =
                        {
                            new KeyFrame<FloatField> { 
                                Property = name, 
                                Value =value,
                                AnimateMode= AnimateMode.EaseOut,
                                Ease=new CubicEase
                                {
                                }},
                        },
                    },
                    new Timeline(1)
                    {
                        KeyFrames =
                        {
                            new KeyFrame<FloatField> {
                                Property = name,
                                Value =0,
                                AnimateMode= AnimateMode.EaseOut,
                                Ease=new CubicEase
                                {
                                }},
                        },
                    }
                }
            };
            storyboard1.Start(obj, TimeSpan.FromSeconds(time), 2);
            
        }

        public void SetShowType(MacMenuItem item)
        {
            switch (ShowType)
            {
                case MacMenuShowType.Left:
                    item.MarginLeft = 0;
                    item.MarginRight = FloatField.Auto;
                    item.MarginTop = FloatField.Auto;
                    item.MarginBottom = FloatField.Auto;
                    break;
                case MacMenuShowType.Top:

                    item.MarginLeft = FloatField.Auto;
                    item.MarginRight = FloatField.Auto;
                    item.MarginTop = 0;
                    item.MarginBottom = FloatField.Auto;
                    break;
                case MacMenuShowType.Right:

                    item.MarginLeft = FloatField.Auto;
                    item.MarginRight = 0;
                    item.MarginTop = FloatField.Auto;
                    item.MarginBottom = FloatField.Auto;
                    break;
                case MacMenuShowType.Botton:

                    item.MarginLeft = FloatField.Auto;
                    item.MarginRight = FloatField.Auto;
                    item.MarginTop = FloatField.Auto;
                    item.MarginBottom = 0;
                    break;
            }
        }
#endif


        public event EventHandler<MouseButtonEventArgs> MacItemMouseDown;
    }
}
